<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="线路名称" prop="routeName">
        <el-input v-model="queryParams.routeName" placeholder="请输入线路名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="起点" prop="startLocation">
        <el-input v-model="queryParams.startLocation" placeholder="请输入起点" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="终点" prop="endLocation">
        <el-input v-model="queryParams.endLocation" placeholder="请输入终点" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['basic:routes:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['basic:routes:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['basic:routes:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['basic:routes:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="routesList" @selection-change="handleSelectionChange">
      <el-table-column label="序号" align="center" type="index" width="68" />
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="线路名称" align="center" prop="routeName" />
      <el-table-column label="起点" align="center" prop="startLocation" />
      <el-table-column label="终点" align="center" prop="endLocation" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['basic:routes:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['basic:routes:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改线路对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="70%">
      <el-form ref="form" :model="form" :rules="rules" label-width="60px">
        <div class="content">
          <div class="search-box">
            <div class="label">关键字搜索</div>
            <el-input v-model="input" placeholder="请输入内容" id="tipinput" clearable></el-input>
          </div>
          <div id="tipinput-suggestions"></div>
          <div id="map-container"></div>
          <div id="panel">
            <el-row :gutter="10">
              <el-col :span="23" class="infoRow">
                <el-form-item label="名称" prop="routeName">
                  <el-input v-model="form.routeName" placeholder="请输入线路名称" clearable />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="5">
              <el-col :span="23" class="infoRow">
                <el-form-item label="起点" prop="startLocation">
                  <el-input v-model="form.startLocation" placeholder="请输入起点" suffix-icon="el-icon-location"
                    @blur="startBlur()" @focus="startFocus()" id="start" />
                </el-form-item>
              </el-col>
              <el-col :span="1" class="infoRow">
                <el-button @click="addWaypoint">+</el-button>
              </el-col>
            </el-row>
            <el-row :gutter="5">
              <div id="wayPoint" v-for="(point, index) in waypoints" :key="index">
                <el-col :span="23" class="infoRow">
                  <el-form-item label="站点">
                    <el-input type="text" v-model="point.stationName" suffix-icon="el-icon-location" placeholder="请输入站点"
                      @blur="handleBlur(index)" @focus="waypointFocus()" />
                  </el-form-item>
                </el-col>
                <el-col :span="1" class="infoRow">
                  <el-button @click="removeWaypoint(index, point)">-</el-button>
                </el-col>
              </div>
            </el-row>
            <el-row :gutter="10">
              <el-col :span="23" class="infoRow">
                <el-form-item label="终点" prop="endLocation">
                  <el-input v-model="form.endLocation" placeholder="请输入终点" suffix-icon="el-icon-location"
                    @blur="endBlur()" @focus="endFocus()" id="end" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="10">
              <el-col :span="23" class="infoRow">
                <el-form-item>
                  <el-button @click="planRoute">规划路线</el-button>
                </el-form-item>
              </el-col>
            </el-row>
          </div>
          <div>
            <!-- 其他内容 -->
          </div>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listRoutes, getRoutes, delRoutes, addRoutes, updateRoutes, addStation, getRouteId, updateStation, getStation, delStation } from "@/api/basic/routes";
import AMapLoader from "@amap/amap-jsapi-loader";
window._AMapSecurityConfig = {
  // 设置安全密钥
  securityJsCode: "0eacb4261b9f35bb139f45c9e4a2298a",
};
export default {
  name: "Routes",
  data() {
    return {
      autocomplete: null,
      input: "", // input的内容
      flag: null,
      map: null,// 
      lnglat: [], // 经纬度数组 [lng,lat] 
      address: "", //地址
      auto: null,
      placeSearch: null,
      markers: [],
      driving: null,
      pointId: null,
      restData: null, //搜索出来的数据存放
      start: "",
      end: "",
      mapClicked: false,
      startFlag: false,
      endFlag: false,
      dialogVisible: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 线路表格数据
      routesList: [],
      projectList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        routeName: null,
        startLocation: null,
        endLocation: null,
      },
      waypoints: [],
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        routeName: [
          { required: true, message: "线路名称不能为空" }
        ],
        startLocation: [
          { required: true, message: "起点不能为空" }
        ],
        endLocation: [
          { required: true, message: "终点不能为空" }
        ],
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询线路列表 */
    getList() {
      this.loading = true;
      this.waypoints = [];
      listRoutes(this.queryParams).then(response => {
        this.routesList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.waypoints = [];
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        routeId: null,
        routeName: null,
        startLocation: null,
        endLocation: null,

      };
      this.waypoints = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.routeId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.initMap()
      this.open = true;
      this.title = "添加线路";
    },
    /** 修改按钮操作 */
    async handleUpdate(row) {
      this.reset();
      this.initMap()
      const routeId = row.routeId || this.ids
      await getRoutes(routeId).then(response => {
        this.form = response.data;
        getStation(routeId).then(response => {
          this.waypoints = response.rows
          this.open = true;
          this.title = "修改线路";
          this.planRoute();
        })
      });

    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.routeId != null) {
            updateRoutes(this.form).then(response => {
              console.log(response.rows, "response")
              console.log(this.waypoints, "this.waypoints")
              for (var i = 0; i < this.waypoints.length; i++) {
                if(this.waypoints[i].stationId==-1){
                  addStation(this.waypoints[i])
                }else{
                  updateStation(this.waypoints[i])
                }
              }
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addRoutes(this.form).then(response => {
              getRouteId(this.form).then(response => {
                console.log(response.data)
                for (var i = 0; i < this.waypoints.length; i++) {
                  this.waypoints[i].routeId = response.data.routeId
                  console.log(this.waypoints[i], "waypoints")
                  addStation(this.waypoints[i]).then(response => {
                    this.$modal.msgSuccess("新增成功");
                    this.open = false;
                    this.getList();
                  })
                }
              })
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const routeIds = row.routeId || this.ids;
      this.$modal.confirm('是否确认删除线路编号为"' + routeIds + '"的数据项？').then(function () {
        return delRoutes(routeIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('basic/routes/export', {
        ...this.queryParams
      }, `routes_${new Date().getTime()}.xlsx`)
    },

    clearMark() {
      this.mapClicked = false;
      this.startFlag = false;
      this.endFlag = false;
    },
    addWaypoint() {
      const index = this.waypoints.length;
      this.waypoints.push({ routeId: this.form.routeId, stationName: '', stationOrder: index, stationId: -1 });
    },

    removeWaypoint(index, row) {
        const stationId = row.stationId;
        this.$modal.confirm('确认删除该站点?').then(function () {
          if(row.stationId!=-1){
            return delStation(stationId);
          }
        }).then(() => {
          this.waypoints.splice(index, 1);
          this.$modal.msgSuccess("删除成功");
        }).catch(() => { });
    },


    initMap() {
      AMapLoader.load({
        key: "697853f8edddc9f02c87266112a449a8", // 申请好的Web端开发者Key，首次调用 load 时必填
        version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
        plugins: ["AMap.AutoComplete", "AMap.PlaceSearch", "AMap.Driving", "AMap.DragRoute", "AMap.Geocoder"], // 需要使用的的插件列表，如比例尺'AMap.Scale'等
      })
        .then((AMap) => {
          console.log(AMap);
          this.map = new AMap.Map("map-container", {
            viewMode: "2D", //  是否为3D地图模式
            zoom: 13, // 初始化地图级别
            center: [114.268691, 30.401227], //中心点坐标
            resizeEnable: true,
          });

          // 关键字查询
          this.searchMap();
          // 监听地图点击事件
          this.map.on("click", this.clickMapHandler);
        })
        .catch((e) => {
          console.log(e);
        });
    },

    async clickMapHandler(e) {
      console.log("点击地图");
      this.lnglat = [e.lnglat.getLng(), e.lnglat.getLat()];
      this.setMarker(this.lnglat);
      if (this.mapClicked) {
        try {
          this.address = await this.getAddress(this.lnglat);
          this.changeWaypoint(this.pointId);
        } catch (error) {
          console.error(error);
        }
      }
      if (this.startFlag) {
        try {
          this.address = await this.getAddress(this.lnglat);
          this.changeStart();
        } catch (error) {
          console.error(error);
        }
      }
      if (this.endFlag) {
        try {
          this.address = await this.getAddress(this.lnglat);
          this.changeEnd();
        } catch (error) {
          console.error(error);
        }
      }
      this.clearMark()
    },

    getAddress(lng) {
      return new Promise((resolve, reject) => {
        var geocoder = new AMap.Geocoder({
          city: '全国'
        });
        var lnglat = lng;
        geocoder.getAddress(lnglat, function (status, result) {
          if (status === 'complete' && result.info === 'OK') {
            resolve(result.regeocode.formattedAddress);
          } else {
            reject(new Error('获取地理位置失败'));
          }
        });
      });
    },
    //  添加标记
    setMarker(lnglat) {
      this.removeMarker();
      console.log("位置", lnglat);
      let marker = new AMap.Marker({
        position: lnglat,
      });
      marker.setMap(this.map);
      this.markers.push(marker);
    },
    // 删除之前后的标记点
    removeMarker() {
      if (this.markers) {
        this.map.remove(this.markers);
      }
    },
    // 关键字查询
    searchMap() {
      // 搜索框自动完成类
      this.auto = new AMap.AutoComplete({
        input: "tipinput", // 使用联想输入的input的id
        output: 'tipinput-suggestions', // 指定起点输入提示结果的容器
      });
      this.placeSearch = new AMap.PlaceSearch({
        map: this.map,
      });
      // 当选中某条搜索记录时触发
      this.auto.on("select", this.selectSite, (result) => {
        console.log(result.tips)
      });

    },
    //当选中某条搜索记录时触发
    selectSite(e) {
      this.lnglat = [e.poi.location.lng, e.poi.location.lat];
      this.placeSearch.setCity(e.poi.adcode);
      this.placeSearch.search(e.poi.name);
    },


    //线路规划方法 
    planRoute() {
      if ((this.form.startLocation != null && this.form.startLocation != '')
        && (this.form.endLocation != null && this.form.endLocation != '')
      ) {
        if (this.driving) {
          this.driving.clear()
        }
        console.log(this.form.startLocation, "start")
        console.log(this.form.endLocation, "end")
        var driv = new AMap.Driving({
          // 驾车路线规划策略，AMap.DrivingPolicy.LEAST_TIME是最快捷模式
          map: this.map,
          policy: AMap.DrivingPolicy.LEAST_TIME
        })
        this.driving = driv
        for (let i = this.waypoints.length - 1; i >= 0; i--) {
          if (this.waypoints[i].stationName === '') {
            this.waypoints.splice(i, 1);
          }
        }
        const waypoints = this.waypoints.map(waypoint => ({ keyword: waypoint.stationName, city: '全国' }));
        console.log(waypoints, "waypoints")
        const points = [
          { keyword: this.form.startLocation, city: '全国' },
          ...waypoints,
          { keyword: this.form.endLocation, city: '全国' }
        ];
        //使用地名规划路线
        this.driving.search(points, (status, result) => {
          console.log("驾车路线规划status=", status);
          if (status === 'complete') {
            console.log('获取驾车数据成功：', result);
          } else {
            console.log('获取驾车数据失败：', result);
          }
        })
        this.clearMark()
      } else {
        this.$refs["form"].validate()
      }
    },

    startFocus() {
      this.clearMark();
    },
    endFocus() {
      this.clearMark();
    },
    waypointFocus() {
      this.clearMark();
    },

    startBlur() {
      this.startFlag = true; // 重置起点标志位
    },
    endBlur() {
      this.endFlag = true; // 重置终点标志位
    },
    handleBlur(id) {
      this.mapClicked = true; // 重置站点标志位
      this.pointId = id;
    },

    changeWaypoint(id) {
      console.log(this.address, "change")
      if (id != null) {
        this.waypoints[id].stationName = this.address;
      }
    },
    changeStart() {
      console.log(this.address, "change")
      this.form.startLocation = this.address;
    },
    changeEnd() {
      console.log(this.address, "change")
      this.form.endLocation = this.address;
    }
  }
};
</script>
<style scoped>
#map-container {
  overflow: hidden;
  width: 500px;
  height: 500px;
  margin: 0;
}

.search-box {

  display: flex;
  justify-content: flex-start;
  align-items: center;
  height: 50px;
  margin-top: -35px;
  padding-bottom: 10px;

  .label {
    width: 100px;
  }
}

.content {
  position: relative;
}

#panel {
  padding-top: 20px;
  padding-left: 15px;
  padding-right: 15px;
  width: 35%;
  position: absolute;
  top: 60px;
  left: 20px;
  background-color: rgba(244, 244, 244, 0.5);
  box-shadow: 0px 2px 4px rgba(0, 0, 0, 0.5);
  border-radius: 10px;
  font-family: Arial, sans-serif;
  color: #333;
}



#map-container {
  overflow: hidden;
  width: 100%;
  height: 650px;
  margin: 0;
}

#tipinput-suggestions {
  position: absolute;
  background-color: white;
  font-size: 25px;
  width: 100%;
  /* top: 100%; 设置为文本框下方 */
  /* left: 0; */
  z-index: 9999;
  /* 设置为较高的值 */
}

.el-col-23 {
  width: 85%;
}
</style>
